package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * TODO
 *
 * @author harmony
 * @description
 * @date 2020/12/9 20:08
 */
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        //定义一个xpath数组
        String [] xpathList = {"//select","//update","//delete","//insert"};
        /**
         * 循环xpath数组
         * 将xpath查询出来的element集合遍历
         * 通过xpath区分sql的类型并封装在mapperStatement
         */
        for(String xpath:xpathList){
            List<Element> list = rootElement.selectNodes(xpath);
            for (Element element : list) {
                String id = element.attributeValue("id");
                String resultType = element.attributeValue("resultType");
                String parameterType = element.attributeValue("parameterType");
                String sql = element.getTextTrim();
                MappedStatement mappedStatement = new MappedStatement();
                mappedStatement.setId(id);
                mappedStatement.setResultType(resultType);
                mappedStatement.setParameterType(parameterType);
                mappedStatement.setSql(sql);
                //sql的类型并封装在mapperStatement
                mappedStatement.setSqlType(xpath.split("//")[1]);
                String key = namespace + "." +id;
                configuration.getMap().put(key,mappedStatement);
            }
        }
    }
}
